package com.aglow.bluetoothspeaker.main.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import com.actions.ibluz.manager.BluzManagerData;
import com.aglow.bluetoothspeaker.R;
import com.aglow.bluetoothspeaker.main.base.BaseActivity;
import com.aglow.bluetoothspeaker.model.bean.AlarmDeleteItem;
import com.aglow.bluetoothspeaker.model.bean.AlarmEditorInfo;
import com.aglow.bluetoothspeaker.model.bean.AlarmEditorItem;
import com.aglow.bluetoothspeaker.model.bean.AlarmSetDate;
import com.aglow.bluetoothspeaker.utils.ToastUtils;
import com.alex.alexswitch.ISwitch;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2018/9/12 11:04
 * 设置闹钟
 */
public class SetDataActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.fl_setdata)
    FrameLayout flSetdata;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.cb_weekdays)
    CheckBox cbWeekdays;
    @BindView(R.id.cb_weekend)
    CheckBox cbWeekend;
    @BindView(R.id.cb_everyday)
    CheckBox cbEveryday;
    @BindView(R.id.cb_mon)
    CheckBox cbMon;
    @BindView(R.id.cb_tue)
    CheckBox cbTue;
    @BindView(R.id.cb_wed)
    CheckBox cbWed;
    @BindView(R.id.cb_thu)
    CheckBox cbThu;
    @BindView(R.id.cb_fri)
    CheckBox cbFri;
    @BindView(R.id.cb_sta)
    CheckBox cbSta;
    @BindView(R.id.cb_sun)
    CheckBox cbSun;
    CheckBox[] checkBoxList = new CheckBox[7];
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.id_apple_lamp)
    ISwitch idAppleLamp;
    @BindView(R.id.id_apple_is_sound)
    ISwitch idAppleIsSound;
    @BindView(R.id.ib_delete)
    ImageButton ibDelete;
    @BindView(R.id.cb_once)
    CheckBox cbOnce;
    private TimePickerView pvTime;
    private boolean[] date = new boolean[]{false, false, false, false, false, false, false}; //日一二三四五六
    private int hour; //时
    private int minute;  //分
    private boolean lampState; //灯光
    private boolean SoundState; //铃声
    private Calendar calendar;
    private int alarmIndex = -1;
    private boolean playState; //开关
    private int position;
    private boolean isShortCutKey;//快捷键开关


    @Override
    public int getLayoutId() {
        return R.layout.activity_alarm_select;
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void initData() {
        initTimePicker();
        setRepeatMode(false);
        checkBoxList[0] = cbSun;
        checkBoxList[1] = cbMon;
        checkBoxList[2] = cbTue;
        checkBoxList[3] = cbWed;
        checkBoxList[4] = cbThu;
        checkBoxList[5] = cbFri;
        checkBoxList[6] = cbSta;
        for (int i = 0; i < checkBoxList.length; i++) {
            checkBoxList[i].setOnCheckedChangeListener(this);
        }
        //设置终端设备的系统时间
        calendar = Calendar.getInstance();
        hour = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);

        Log.i("setData", "初始化成功...");
    }

    @Override
    public void initView() {
        pvTime.show(btnSave);


    }

    @Override
    public void addViewListener() {
        idAppleLamp.setOnISwitchOnClickListener(new ISwitch.ISwitchOnClickListeners() {
            @Override
            public void open() {
                lampState = true;
            }

            @Override
            public void close() {
                lampState = false;
            }
        });
        idAppleIsSound.setOnISwitchOnClickListener(new ISwitch.ISwitchOnClickListeners() {
            @Override
            public void open() {
                SoundState = true;
                Log.i("sss", "Sound = " + SoundState);
            }

            @Override
            public void close() {
                SoundState = false;
                Log.i("sss", "Sound = " + SoundState);
            }
        });
        cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i("setData", "once checkedchanged 执行");
                if (isChecked) {
                    cbEveryday.setChecked(false);
                    cbWeekend.setChecked(false);
                    cbWeekdays.setChecked(false);
                    setCheckBoxDate(false);
                    setRepeatMode(false);
                    Log.i("setData", "date = " + Arrays.toString(date));
                }
            }
        });

    }


    /**
     * 进入编辑界面
     *
     * @param info
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void OnEditorInfo(AlarmEditorInfo info) {
        hour = info.getHour();
        minute = info.getMinute();
        boolean[] date = info.getDate();
        lampState = info.isLampState();
        SoundState = info.isSoundState();
        alarmIndex = info.getAlarmIndex();
        position = info.getPosition();
        playState = info.isPlayState();
        Log.i("edit", "SoundState = " + SoundState);
        Log.i("edit", "lampState = " + lampState);
        if (lampState) {
            idAppleLamp.setIsOpen(lampState);
        }
        if (SoundState) {
            idAppleIsSound.setIsOpen(SoundState);
        }
        //处理onec的按钮界面数据
        int k = 0;
        for (int i = 0; i < date.length; i++) {
            boolean b = false;
            if (date[i]) {
                checkBoxList[i].setChecked(true);
            } else {
                k++;
            }

            if (k == date.length) {
                cbOnce.setChecked(true);
            }

        }
        //设置时间
        calendar.set(2010, 1, 1, hour, minute);
        pvTime.setDate(calendar);
        Log.i("set", "OK");
        if (checkBoxList[0].isChecked() && checkBoxList[1].isChecked() && checkBoxList[2].isChecked() &&
                checkBoxList[3].isChecked() && checkBoxList[4].isChecked() && checkBoxList[5].isChecked() && checkBoxList[6].isChecked()) {//everdays
            cbEveryday.performClick();
            isShortCutKey = true;

        } else if (checkBoxList[1].isChecked() && checkBoxList[2].isChecked() &&
                checkBoxList[3].isChecked() && checkBoxList[4].isChecked() && checkBoxList[5].isChecked() && !checkBoxList[6].isChecked() &&
                !checkBoxList[0].isChecked()) {//weekdays

            Log.i("setData", "weekdays 点击事件执行");
            cbWeekdays.performClick();
            isShortCutKey = true;
        } else if (checkBoxList[0].isChecked() && checkBoxList[6].isChecked() && !checkBoxList[1].isChecked() && !checkBoxList[2].isChecked() && !checkBoxList[3].isChecked() && !checkBoxList[4].isChecked() &&
                !checkBoxList[5].isChecked()) {//weekend
            cbWeekend.performClick();
            isShortCutKey = true;
        }
        EventBus.getDefault().removeStickyEvent(info);
        Log.i("setData", "進入編輯界面");
    }

    /**
     * 初始化设置时间选择器
     **/
    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();

        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 0, 23);

        Calendar endDate = Calendar.getInstance();
        endDate.set(2019, 11, 28);
        //时间选择器
        pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调

        })
                .setLayoutRes(R.layout.pickerview_custom, new CustomListener() {
                    @Override
                    public void customLayout(View view) {
                    }
                })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {//获取时间
                        Log.i("index", "date:" + getTime(date));
                        String dateTime = getTime(date);
                        hour = Integer.parseInt(dateTime.substring(0, dateTime.indexOf(":")));
                        Log.i("index", "hour:" + hour);
                        minute = Integer.parseInt(dateTime.substring(dateTime.indexOf(":") + 1, dateTime.length()));
                        Log.i("index", "minute:" + minute);
                    }
                })
                .setType(new boolean[]{false, false, false, true, true, false})
                .setLabel("", "", "", "\n\t\n\t:", "", "") //设置空字符串以隐藏单位提示   hide label
                .setDividerColor(Color.DKGRAY)
                .isCenterLabel(true)
                .setContentTextSize(27)
                .setDate(selectedDate)
                .isCyclic(true)
                .setRangDate(startDate, selectedDate)
                .setDecorView(flSetdata)//非dialog模式下,设置ViewGroup, pickerView将会添加到这个ViewGroup中
                .setBackgroundId(0x00000000)
                .setDividerColor(0x00fffff)
                .setOutSideCancelable(false)
                .setBgColor(0x00fffff)
                .setLineSpacingMultiplier(1.2f)
                .build();

        pvTime.setKeyBackCancelable(false);//系统返回键监听屏蔽掉

    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }


    @OnClick({R.id.btn_cancel, R.id.cb_weekdays, R.id.cb_weekend, R.id.cb_everyday, R.id.cb_mon, R.id.cb_tue,
            R.id.cb_wed, R.id.cb_thu, R.id.cb_fri, R.id.cb_sta, R.id.cb_sun, R.id.btn_save, R.id.ib_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.cb_weekdays://工作日--星期一到星期五
                Log.i("setData", "执行 weekdaysOnviewClick");
                setCheckBoxDate(false);
                cbEveryday.setChecked(false);
                cbWeekend.setChecked(false);
                cbOnce.setChecked(false);
                if (cbWeekdays.isChecked()) {
                    setRepeatMode(false);
                    date[1] = true;
                    date[2] = true;
                    date[3] = true;
                    date[4] = true;
                    date[5] = true;
                } else {
                    setRepeatMode(false);
                }
                break;
            case R.id.cb_weekend:
                setCheckBoxDate(false);
                cbEveryday.setChecked(false);
                cbWeekdays.setChecked(false);
                cbOnce.setChecked(false);
                if (cbWeekend.isChecked()) {
                    setRepeatMode(false);
                    date[0] = true;
                    date[6] = true;
                } else {
                    setRepeatMode(false);
                }
                break;
            case R.id.cb_everyday:
                setCheckBoxDate(false);
                cbWeekend.setChecked(false);
                cbWeekdays.setChecked(false);
                cbOnce.setChecked(false);
                if (cbEveryday.isChecked()) {
                    for (int i = 0; i < date.length; i++) {
                        date[i] = true;
                    }
                } else {
                    setRepeatMode(false);
                }

                break;
            case R.id.btn_save:
                if (!lampState && !SoundState) {
                    ToastUtils.showShortToast("Please select Daylight lamp or Sound !");
                    return;
                }
                for (int i = 0; i < date.length; i++) {
                    Log.i("setData", "date =" + date[i]);
                    if (date[i] == true || cbOnce.isChecked()) {
                        if (alarmIndex == -1) {
                            EventBus.getDefault().postSticky(new AlarmSetDate(date, hour, minute, lampState, SoundState));
                        } else {
                            EventBus.getDefault().postSticky(new AlarmEditorItem(date, hour, minute, lampState, SoundState, position, playState));
                        }
                        finish();
                        return;
                    }
                }

                ToastUtils.showShortToast("Please select date!");

                break;
            case R.id.ib_delete:
                if (alarmIndex != -1) {
                    EventBus.getDefault().postSticky(new AlarmDeleteItem(position, alarmIndex));
                    finish();
                }
                break;


        }
    }

    private void setCheckBoxDate(boolean state) {
        cbMon.setChecked(state);
        cbTue.setChecked(state);
        cbThu.setChecked(state);
        cbFri.setChecked(state);
        cbWed.setChecked(state);
        cbSta.setChecked(state);
        cbSun.setChecked(state);
    }

    private void setRepeatMode(boolean mode) {
        date[0] = mode;
        date[1] = mode;
        date[2] = mode;
        date[3] = mode;
        date[4] = mode;
        date[5] = mode;
        date[6] = mode;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isShortCutKey) {
            isShortCutKey = false;
            setRepeatMode(false);
        }
        //互斥
        if (isChecked) {
            cbWeekdays.setChecked(false);
            cbWeekend.setChecked(false);
            cbEveryday.setChecked(false);
            if (cbOnce.isChecked()) {
                cbOnce.setChecked(false);
            }

        }
        switch (buttonView.getId()) {
            case R.id.cb_mon:
                onClickSetDate(1, isChecked);
                break;
            case R.id.cb_tue:
                onClickSetDate(2, isChecked);
                break;
            case R.id.cb_wed:
                onClickSetDate(3, isChecked);
                break;
            case R.id.cb_thu:
                onClickSetDate(4, isChecked);
                break;
            case R.id.cb_fri:
                onClickSetDate(5, isChecked);
                break;
            case R.id.cb_sta:
                onClickSetDate(6, isChecked);
                break;
            case R.id.cb_sun:
                onClickSetDate(0, isChecked);
                break;
        }

    }

    private void onClickSetDate(int number, boolean isChecked) {
        date[number] = isChecked;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pvTime = null;
    }


}

